<template>
  <div class="members-consumption">
    <h3>消费明细</h3>

    <!-- 用户选择功能 -->
    <div class="user-selection">
      <label for="user-select">选择用户:</label>
      <select id="user-select" v-model="selectedUser">
        <option value="">全部用户</option>
        <option v-for="user in users" :key="user.id" :value="user.id">{{ user.name }}</option>
      </select>
    </div>

    <!-- 筛选和搜索功能 -->
    <div class="filter-section">
      <label for="date-range">选择日期范围:</label>
      <input type="date" id="start-date" v-model="startDate" />
      <input type="date" id="end-date" v-model="endDate" />
      <button @click="filterRecords">筛选</button>
    </div>

    <!-- 消费记录列表 -->
    <table class="consumption-table">
      <thead>
        <tr>
          <th>消费日期</th>
          <th>消费描述</th>
          <th>消费金额</th>
          <th>支付方式</th>
          <th>订单号</th>
          <th>商品详情</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="record in filteredRecords" :key="record.id">
          <td>{{ record.date }}</td>
          <td>{{ record.description }}</td>
          <td>{{ record.amount }}</td>
          <td>{{ record.paymentMethod }}</td>
          <td>{{ record.orderId }}</td>
          <td>{{ record.productDetails }}</td>
        </tr>
      </tbody>
    </table>

    <!-- 分页功能 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>

    <!-- 总计信息 -->
    <div class="total-info">
      <p>总消费金额: {{ totalAmount }}</p>
    </div>

    <!-- 导出功能 -->
    <div class="export-section">
      <button @click="exportData">导出数据</button>
    </div>

    <!-- 消费趋势图表 -->
    <div class="chart-section">
      <line-chart :data="chartData"></line-chart>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import LineChart from './LineChart.vue'
import { ElMessage } from 'element-plus'

// 模拟用户数据
const users = [
  { id: 1, name: '用户A' },
  { id: 2, name: '用户B' }
]

// 模拟消费记录数据（建议后期替换为接口获取）
const records = [
  {
    id: 1,
    userId: 1,
    date: '2023-10-01',
    description: '商品A',
    amount: '100.00',
    paymentMethod: '支付宝',
    orderId: '12345',
    productDetails: '商品A详情'
  },
  {
    id: 2,
    userId: 2,
    date: '2023-10-02',
    description: '商品B',
    amount: '200.00',
    paymentMethod: '微信支付',
    orderId: '67890',
    productDetails: '商品B详情'
  }
]

// 用户选择与筛选条件
const selectedUser = ref('')
const startDate = ref('')
const endDate = ref('')
const currentPage = ref(1)
const pageSize = 10

// 过滤逻辑
const filteredRecords = computed(() => {
  let result = [...records]

  if (selectedUser.value) {
    result = result.filter(record => record.userId === parseInt(selectedUser.value))
  }

  if (startDate.value) {
    result = result.filter(record => new Date(record.date) >= new Date(startDate.value))
  }

  if (endDate.value) {
    result = result.filter(record => new Date(record.date) <= new Date(endDate.value))
  }

  return result.slice((currentPage.value - 1) * pageSize, currentPage.value * pageSize)
})

// 分页计算
const totalPages = computed(() => Math.max(1, Math.ceil(filteredRecords.value.length / pageSize)))

// 总消费金额
const totalAmount = computed(() => {
  return filteredRecords.value.reduce((total, record) => total + parseFloat(record.amount), 0).toFixed(2)
})

// 分页控制
const filterRecords = () => {
  currentPage.value = 1
}

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

// 图表数据
const chartData = computed(() => {
  const data = {}
  filteredRecords.value.forEach(record => {
    const date = new Date(record.date).toLocaleDateString()
    data[date] = (data[date] || 0) + parseFloat(record.amount)
  })
  return {
    labels: Object.keys(data),
    datasets: [{
      label: '消费金额趋势',
      data: Object.values(data),
      borderColor: '#409EFF',
      backgroundColor: 'rgba(64, 158, 255, 0.2)',
      fill: true,
      tension: 0.1
    }]
  }
})

// 导出 CSV 功能
const exportData = () => {
  if (!filteredRecords.value.length) {
    ElMessage.warning('暂无数据可导出')
    return
  }

  // 构建 CSV 内容
  const headers = ['消费日期', '消费描述', '消费金额', '支付方式', '订单号', '商品详情']
  const csvRows = []

  // 添加表头
  csvRows.push(headers.join(','))

  // 添加数据行
  filteredRecords.value.forEach(record => {
    const row = [
      `"${record.date}"`,
      `"${record.description}"`,
      `"${record.amount}"`,
      `"${record.paymentMethod}"`,
      `"${record.orderId}"`,
      `"${record.productDetails}"`
    ]
    csvRows.push(row.join(','))
  })

  // 生成 Blob 并下载
  const csvString = csvRows.join('\r\n')
  const blob = new Blob([`\uFEFF${csvString}`], { type: 'text/csv;charset=utf-8;' }) // \uFEFF 解决 Excel 打开乱码问题
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.setAttribute('href', url)

  // 自定义文件名（包含时间范围或用户名）
  const userLabel = selectedUser.value ? `用户_${users.find(u => u.id == selectedUser.value)?.name}` : '全部用户'
  const dateLabel = startDate.value && endDate.value ? `${startDate.value}_至_${endDate.value}` : "全部日期"
  const filename = `消费明细_${userLabel}_${dateLabel}.csv`

  link.setAttribute('download', filename)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  ElMessage.success('导出成功！')
}
</script>

<style scoped>
.members-consumption {
  padding: 20px;
}

.user-selection,
.filter-section {
  margin-bottom: 20px;
}

.consumption-table {
  width: 100%;
  border-collapse: collapse;
}

.consumption-table th,
.consumption-table td {
  border: 1px solid #ddd;
  padding: 8px;
}

.consumption-table th {
  background-color: #f2f2f2;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.total-info,
.export-section,
.chart-section {
  margin-top: 20px;
}

.total-info {
  font-weight: bold;
}
</style>